import { Elysia } from 'elysia';
import { processImageUpload, processFileUpload, uploadMiddleware, deleteFile, getFileInfo } from '../middleware/upload';
import { guestAccessMiddleware } from '../middleware/auth';

export const uploadRoutes = new Elysia({ prefix: '/upload' })
  // 需要登录权限的路由（游客可查看，管理员可编辑）
  .use(guestAccessMiddleware())
  
  // 上传单个图片
  .post('/image', async ({ body, set }) => {
    try {
      const formData = body as any;
      const file = formData.file;
      
      if (!file || !(file instanceof File)) {
        set.status = 400;
        return {
          success: false,
          message: '请选择要上传的图片文件',
          code: 'NO_FILE'
        };
      }
      
      const result = await processImageUpload(file, {
        maxWidth: 1920,
        maxHeight: 1080,
        quality: 85,
        format: 'webp'
      });
      
      if (!result.success) {
        set.status = 400;
        return {
          success: false,
          message: result.error || '图片上传失败',
          code: 'UPLOAD_FAILED'
        };
      }
      
      return {
        success: true,
        message: '图片上传成功',
        data: {
          url: result.url,
          filePath: result.filePath
        }
      };
    } catch (error) {
      console.error('Image upload error:', error);
      set.status = 500;
      return {
        success: false,
        message: '服务器内部错误',
        code: 'INTERNAL_ERROR'
      };
    }
  }, {
    detail: {
      tags: ['文件上传'],
      summary: '上传图片',
      description: '上传单个图片文件，支持自动压缩和格式转换'
    }
  })
  
  // 上传多个图片
  .post('/images', async ({ body, set }) => {
    try {
      const formData = body as any;
      const files = formData.files;
      
      if (!files || !Array.isArray(files) || files.length === 0) {
        set.status = 400;
        return {
          success: false,
          message: '请选择要上传的图片文件',
          code: 'NO_FILES'
        };
      }
      
      const results = [];
      const errors = [];
      
      for (let i = 0; i < files.length; i++) {
        const file = files[i];
        if (!(file instanceof File)) {
          errors.push(`文件 ${i + 1}: 无效的文件格式`);
          continue;
        }
        
        const result = await processImageUpload(file, {
          maxWidth: 1920,
          maxHeight: 1080,
          quality: 85,
          format: 'webp'
        });
        
        if (result.success) {
          results.push({
            url: result.url,
            filePath: result.filePath,
            originalName: file.name
          });
        } else {
          errors.push(`文件 ${file.name}: ${result.error}`);
        }
      }
      
      return {
        success: true,
        message: `成功上传 ${results.length} 个文件${errors.length > 0 ? `，${errors.length} 个文件失败` : ''}`,
        data: {
          uploaded: results,
          errors: errors
        }
      };
    } catch (error) {
      console.error('Multiple images upload error:', error);
      set.status = 500;
      return {
        success: false,
        message: '服务器内部错误',
        code: 'INTERNAL_ERROR'
      };
    }
  }, {
    detail: {
      tags: ['文件上传'],
      summary: '上传多个图片',
      description: '批量上传多个图片文件'
    }
  })
  
  // 上传文档文件
  .post('/document', async ({ body, set }) => {
    try {
      const formData = body as any;
      const file = formData.file;
      
      if (!file || !(file instanceof File)) {
        set.status = 400;
        return {
          success: false,
          message: '请选择要上传的文件',
          code: 'NO_FILE'
        };
      }
      
      const result = await processFileUpload(file);
      
      if (!result.success) {
        set.status = 400;
        return {
          success: false,
          message: result.error || '文件上传失败',
          code: 'UPLOAD_FAILED'
        };
      }
      
      return {
        success: true,
        message: '文件上传成功',
        data: {
          url: result.url,
          filePath: result.filePath,
          originalName: file.name,
          size: file.size,
          type: file.type
        }
      };
    } catch (error) {
      console.error('Document upload error:', error);
      set.status = 500;
      return {
        success: false,
        message: '服务器内部错误',
        code: 'INTERNAL_ERROR'
      };
    }
  }, {
    detail: {
      tags: ['文件上传'],
      summary: '上传文档',
      description: '上传文档文件（PDF、文本等）'
    }
  })
  
  // 上传产品图片（特殊处理）
  .post('/product-image', async ({ body, set }) => {
    try {
      const formData = body as any;
      const file = formData.file;
      
      if (!file || !(file instanceof File)) {
        set.status = 400;
        return {
          success: false,
          message: '请选择要上传的产品图片',
          code: 'NO_FILE'
        };
      }
      
      // 产品图片使用特殊的尺寸和质量设置
      const result = await processImageUpload(file, {
        maxWidth: 800,
        maxHeight: 600,
        quality: 90,
        format: 'webp'
      });
      
      if (!result.success) {
        set.status = 400;
        return {
          success: false,
          message: result.error || '产品图片上传失败',
          code: 'UPLOAD_FAILED'
        };
      }
      
      return {
        success: true,
        message: '产品图片上传成功',
        data: {
          url: result.url,
          filePath: result.filePath
        }
      };
    } catch (error) {
      console.error('Product image upload error:', error);
      set.status = 500;
      return {
        success: false,
        message: '服务器内部错误',
        code: 'INTERNAL_ERROR'
      };
    }
  }, {
    detail: {
      tags: ['文件上传'],
      summary: '上传产品图片',
      description: '上传产品展示图片，自动优化尺寸和质量'
    }
  })
  
  // 上传案例图片（特殊处理）
  .post('/case-image', async ({ body, set }) => {
    try {
      const formData = body as any;
      const file = formData.file;
      
      if (!file || !(file instanceof File)) {
        set.status = 400;
        return {
          success: false,
          message: '请选择要上传的案例图片',
          code: 'NO_FILE'
        };
      }
      
      // 案例图片使用高质量设置
      const result = await processImageUpload(file, {
        maxWidth: 1200,
        maxHeight: 800,
        quality: 95,
        format: 'webp'
      });
      
      if (!result.success) {
        set.status = 400;
        return {
          success: false,
          message: result.error || '案例图片上传失败',
          code: 'UPLOAD_FAILED'
        };
      }
      
      return {
        success: true,
        message: '案例图片上传成功',
        data: {
          url: result.url,
          filePath: result.filePath
        }
      };
    } catch (error) {
      console.error('Case image upload error:', error);
      set.status = 500;
      return {
        success: false,
        message: '服务器内部错误',
        code: 'INTERNAL_ERROR'
      };
    }
  }, {
    detail: {
      tags: ['文件上传'],
      summary: '上传产品图片',
      description: '上传产品展示图片，自动优化尺寸和质量'
    }
  })
  
  // 删除文件 - 需要管理员权限
  .delete('/file', async ({ body, set, user }) => {
    // 检查权限
    const { checkReadOnlyAccess } = await import('../middleware/auth');
    const accessCheck = checkReadOnlyAccess(user, 'DELETE');
    if (!accessCheck.allowed) {
      set.status = 403;
      return {
        success: false,
        message: accessCheck.message,
        code: 'PERMISSION_DENIED'
      };
    }
    try {
      const { filePath } = body as { filePath: string };
      
      if (!filePath) {
        set.status = 400;
        return {
          success: false,
          message: '请提供文件路径',
          code: 'MISSING_FILE_PATH'
        };
      }
      
      const result = await deleteFile(filePath);
      
      if (result.success) {
        return {
          success: true,
          message: '文件删除成功'
        };
      } else {
        set.status = 400;
        return {
          success: false,
          message: result.error || '文件删除失败',
          code: 'DELETE_FAILED'
        };
      }
    } catch (error) {
      console.error('Delete file route error:', error);
      set.status = 500;
      return {
        success: false,
        message: '服务器内部错误',
        code: 'INTERNAL_ERROR'
      };
    }
  }, {
    detail: {
      tags: ['文件管理'],
      summary: '删除文件',
      description: '删除指定的文件（需要管理员权限）'
    }
  })
  
  // 获取文件信息
  .get('/file/info', async ({ query, set }) => {
    try {
      const { filePath } = query as { filePath: string };
      
      if (!filePath) {
        set.status = 400;
        return {
          success: false,
          message: '请提供文件路径',
          code: 'MISSING_FILE_PATH'
        };
      }
      
      const result = await getFileInfo(filePath);
      
      if (result.success) {
        return {
          success: true,
          data: result.info
        };
      } else {
        set.status = 404;
        return {
          success: false,
          message: result.error || '获取文件信息失败',
          code: 'FILE_INFO_FAILED'
        };
      }
    } catch (error) {
      console.error('Get file info route error:', error);
      set.status = 500;
      return {
        success: false,
        message: '服务器内部错误',
        code: 'INTERNAL_ERROR'
      };
    }
  }, {
    detail: {
      tags: ['文件管理'],
      summary: '获取文件信息',
      description: '获取指定文件的详细信息'
    }
  });